// 在原有代码基础上增加唤醒功能
class RemoteBlooth extends {
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 3;
  private wakeupTimeout = 5000; // 5秒唤醒超时

  // 尝试唤醒设备
  async tryWakeupDevice(deviceId: string): Promise<boolean> {
    try {
      // 发送唤醒广播（标准中的广播类型2）
      const wakeupCommand = this.createWakeupCommand(deviceId);
      await bluetooth.sendBroadcast(wakeupCommand);

      // 等待设备响应
      const wokeUp = await this.waitForWakeupResponse(deviceId);
      if (wokeUp) {
        await bluetooth.connect(deviceId);
        return true;
      }
      return false;
    } catch (err) {
      console.error('唤醒设备失败:', err);
      return false;
    }
  }

  // 创建唤醒命令（根据GY/T 407—2024标准）
  private createWakeupCommand(deviceId: string): ArrayBuffer {
    const buffer = new ArrayBuffer(7);
    const view = new DataView(buffer);
    view.setUint8(0, 0b00010001); // 类型2 + 唤醒标志
    // 填充源地址和目标地址（根据实际协议）
    return buffer;
  }

  // 等待唤醒响应
  private waitForWakeupResponse(deviceId: string): Promise<boolean> {
    return new Promise((resolve) => {
      const timer = setTimeout(() => resolve(false), this.wakeupTimeout);

      bluetooth.once('wakeupResponse', (responseDeviceId) => {
        if (responseDeviceId === deviceId) {
          clearTimeout(timer);
          resolve(true);
        }
      });
    });
  }

  // 带唤醒功能的重连方法
  async reconnectWithWakeup(deviceId: string): Promise<boolean> {
    while (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;

      try {
        // 1. 尝试普通连接
        await bluetooth.connect(deviceId);
        return true;
      } catch (connectError) {
        console.log(`普通连接失败，尝试唤醒 (尝试 ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);

        // 2. 尝试唤醒
        const wokeUp = await this.tryWakeupDevice(deviceId);
        if (wokeUp) return true;

        // 3. 等待间隔后重试
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
    }

    console.error(`重连失败，已达最大尝试次数 ${this.maxReconnectAttempts}`);
    return false;
  }
}
